import { kebabCase, pickBy } from 'lodash-es';
import { setCssVar } from './util';

import { theme } from 'ant-design-vue';
import { AliasToken } from 'ant-design-vue/es/theme/interface';
import convertLegacyToken from 'ant-design-vue/lib/theme/convertLegacyToken';
import { ThemeEnum } from '/@/enums/appEnum';

import { exportDefaultCssVars, exportDarkCssVars, prefixCls } from '/@/settings/designSetting';
import { isEmpty, isNumber } from '/@/utils/is';

/**
 * 公开主题配色，用于自定义组件同步主题色
 *
 */
export function updateThemeConfig(token?: Partial<AliasToken>) {
  const { getThemeConfig, getDarkMode } = useRootSetting();
  const { defaultAlgorithm, darkAlgorithm, defaultSeed } = theme;
  const isDark = getDarkMode.value === ThemeEnum.DARK;

  const cssVars = { ...exportDefaultCssVars, ...(isDark ? exportDarkCssVars : {}) };

  //完整版主题样式
  let fullCssVars = (isDark ? darkAlgorithm : defaultAlgorithm)({
    ...defaultSeed,
    ...pickBy(cssVars, (v) => !isEmpty(v)),
    ...pickBy({ ...getThemeConfig.value.token, ...token }, (v) => !isEmpty(v)),
  });

  //部分样式不会被替换，所以默认生成后的样式要再次用自定义的覆盖下
  fullCssVars = {
    ...fullCssVars,
    ...pickBy(cssVars, (v) => !isEmpty(v)),
    ...pickBy({ ...getThemeConfig.value.token, ...token }, (v) => !isEmpty(v)),
  };

  //自定义深色模式的背景色
  if (isDark) {
    const val = token?.colorBgBase || getThemeConfig.value.token?.colorBgBase;
    if (val) fullCssVars.colorBgBase = val;
  }

  // const filterEmpty = pickBy(fullCssVars, !isEmpty);

  //如果需要 兼容v3
  const v3Token = convertLegacyToken(fullCssVars);
  console.log(v3Token, fullCssVars);

  /**
   * 以下为 自定义公开的颜色，不属于antd内置的
   */

  const exportCustomCssVars = {
    appBgContent: '#f7f8fa',
  };

  for (const key in cssVars) {
    const cssVarName = `--ant-${kebabCase(key)}`;

    //如果token中没有对应的值，则使用预设默认值
    //数值要追加'px'
    const val = fullCssVars[key];
    setCssVar(cssVarName, isNumber(val) ? val + 'px' : val);
  }

  for (const key in exportCustomCssVars) {
    const cssVarName = `--${prefixCls}-${kebabCase(key)}`;
    const val = exportCustomCssVars[key];
    //如果token中没有对应的值，则使用预设默认值
    setCssVar(cssVarName, isNumber(val) ? val + 'px' : val);
  }
}
